package util

import (
	"IrisStandard/config"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const LoginTokenExpireMinute = 120

const CaptchaTokenExpireMinute = 15

func GenerateLoginToken(userId string, min time.Duration) string {
	claims := jwt.MapClaims{
		"userId": userId,
		"exp": time.Now().Add(time.Minute * min).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, _ := token.SignedString([]byte(config.Setting.SecretKey.Login))
	return tokenString
}

func CheckLoginToken(tokenString string) (string, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Setting.SecretKey.Login), nil
	})
	//token错误
	if err != nil {
		return "", err
	} else {
		data := token.Claims.(jwt.MapClaims)
		return data["userId"].(string), nil
	}
}

func GenerateCaptchaToken(phone string, captcha string, min time.Duration) string {
	claims := jwt.MapClaims{
		"phone": phone,
		"captcha": captcha,
		"exp": time.Now().Add(time.Minute * min).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, _ := token.SignedString([]byte(config.Setting.SecretKey.Captcha))
	return tokenString
}

func CheckCaptchaToken(tokenString string) (string, string, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Setting.SecretKey.Captcha), nil
	})
	//token错误
	if err != nil {
		return "", "", err
	} else {
		data := token.Claims.(jwt.MapClaims)
		return data["phone"].(string), data["captcha"].(string), nil
	}
}
